package cn.net.api;

import java.math.BigDecimal;
import java.util.Scanner;

/*本类用于浮点数运算不均确问题*/
public class TestBigDecimal {
    public static void main(String[] args) {
       // f1();//暴露：+、-、*、/                         System.out.println(a+b);
        f2();//解决：add、subtract\multiply\divide          bd3 = bd1.add(bd2);
    }

    private static void f2() {
        double a = new Scanner(System.in).nextDouble();
        double b = new Scanner(System.in).nextDouble();
        /*注意有坑，不要使用double构造方法，因为不精确，需使用String类型的参数构造方法*/
        BigDecimal bd1 = new BigDecimal(a+"");//double转String可以直接拼接一个字符串
        BigDecimal bd2 = new BigDecimal(b+"");// new BigDecimal(Double d)/(String s)
        BigDecimal bd3;

        bd3 = bd1.add(bd2);
        System.out.println(bd3);

        bd3 = bd1.subtract(bd2);
        System.out.println(bd3);

        bd3 = bd1.multiply(bd2);
        System.out.println(bd3);
       // bd3 = bd1.divide(bd2);//需要设置保留位数和舍弃规则
        bd3=bd1.divide(bd2,3,BigDecimal.ROUND_HALF_UP);//1/0.3=3.333
        System.out.println(bd3);

        bd3=bd1.setScale(3,BigDecimal.ROUND_HALF_UP);
        System.out.println(bd3);//1.000

    }

    private static void f1() {
        double a = new Scanner(System.in).nextDouble();
        double b = new Scanner(System.in).nextDouble();
        System.out.println(a+b);
        System.out.println(a-b);
        System.out.println(a*b);
        System.out.println(a/b);//需要设置保留位数和舍弃规则
    }
}
